
<template>
  <div class="my-schedule-container">
    <div class="header">
      <h2>我的课程表</h2>
    </div>

    <div v-if="loading" class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>

    <div v-else-if="scheduleData.length === 0" class="empty-container">
      <el-empty description="暂无排课信息" />
    </div>

    <div v-else class="schedule-table-wrapper">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="timeSlot" label="时间" width="120" fixed left />
        <el-table-column prop="monday" label="星期一" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.monday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="tuesday" label="星期二" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.tuesday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="wednesday" label="星期三" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.wednesday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="thursday" label="星期四" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.thursday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="friday" label="星期五" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.friday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="saturday" label="星期六" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.saturday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sunday" label="星期日" width="180">
          <template #default="scope">
            <div v-for="(course, index) in scope.row.sunday" :key="index" class="course-item">
              <div class="course-name">{{ course.className }}</div>
              <div class="course-info">{{ course.classroom }}</div>
              <div class="course-info">{{ course.courseName }}</div>
              <div class="course-week">{{ course.startWeek }}-{{ course.endWeek }}周</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElLoading, ElEmpty } from 'element-plus'
import 'element-plus/dist/index.css'
import auth from '../../../utils/auth'
import scheduleApi from '../../../api/schedule.js'

export default {
  name: 'MySchedule',
  components: {
    ElTable,
    ElTableColumn,
    ElLoading,
    ElEmpty
  },
  setup() {
    const loading = ref(false)
    const scheduleData = ref([])
    const tableData = ref([])

    // 时间段数组，对应1-12节课，固定的时间段结构
    const timeSlots = [
      { startTime: 1, endTime: 2, display: '1-2节' },
      { startTime: 3, endTime: 4, display: '3-4节' },
      { startTime: 5, endTime: 6, display: '5-6节' },
      { startTime: 7, endTime: 8, display: '7-8节' },
      { startTime: 9, endTime: 10, display: '9-10节' },
      { startTime: 11, endTime: 12, display: '11-12节' }
    ]

    // 获取课程表数据
    const getScheduleData = async () => {
      loading.value = true
      try {
        // 获取当前登录用户的用户名
        const teacherName = auth.getUserName ? auth.getUserName() : ''

        // 调用API获取所有排课数据（不分页）
        const response = await scheduleApi.getSchedulePage(1, 100, '', '', teacherName)

        if (response && response.code === 200) {
          console.log('获取到的课程数据:', response.data.records)
          scheduleData.value = response.data.records || []
          // 构建课程表数据
          buildTableData()
        } else {
          console.error('获取排课数据失败:', response?.msg || '未知错误')
        }
      } catch (error) {
        console.error('请求排课数据时发生错误:', error)
      } finally {
        loading.value = false
      }
    }

    // 构建课程表数据结构
    const buildTableData = () => {
      // 初始化表格数据，每个时间段使用空数组
      const newTableData = timeSlots.map(slot => ({
        timeSlot: slot.display,
        monday: [],
        tuesday: [],
        wednesday: [],
        thursday: [],
        friday: [],
        saturday: [],
        sunday: []
      }))

      // 填充课程数据
      scheduleData.value.forEach((course, index) => {

        // 检查是否需要拆分时间段
        if (course.endTime - course.startTime > 1) {
          // 找到所有包含在这个长时间段内的标准时间段
          timeSlots.forEach((slot, slotIndex) => {
            // 如果标准时间段的开始和结束时间都在课程的时间段内
            if (slot.startTime >= course.startTime && slot.endTime <= course.endTime) {
              // 创建课程的副本，避免修改原始数据
              const courseCopy = { ...course }
              // 更新副本的时间段为标准时间段
              courseCopy.startTime = slot.startTime
              courseCopy.endTime = slot.endTime
              // 根据星期几将课程副本添加到对应的数组中
              switch (course.day) {
                case 1:
                  newTableData[slotIndex].monday.push(courseCopy)
                  break
                case 2:
                  newTableData[slotIndex].tuesday.push(courseCopy)
                  break
                case 3:
                  newTableData[slotIndex].wednesday.push(courseCopy)
                  break
                case 4:
                  newTableData[slotIndex].thursday.push(courseCopy)
                  break
                case 5:
                  newTableData[slotIndex].friday.push(courseCopy)
                  break
                case 6:
                  newTableData[slotIndex].saturday.push(courseCopy)
                  break
                case 7:
                  newTableData[slotIndex].sunday.push(courseCopy)
                  break
              }
            }
          })
        } else {
          // 普通时间段处理
          // 找到对应的时间段
          const slotIndex = timeSlots.findIndex(slot =>
              slot.startTime === course.startTime && slot.endTime === course.endTime
          )

          if (slotIndex !== -1) {
            console.log(`课程${index + 1}放入时间段${slotIndex + 1}`)
            // 根据星期几将课程添加到对应的数组中
            switch (course.day) {
              case 1:
                newTableData[slotIndex].monday.push(course)
                break
              case 2:
                newTableData[slotIndex].tuesday.push(course)
                break
              case 3:
                newTableData[slotIndex].wednesday.push(course)
                break
              case 4:
                newTableData[slotIndex].thursday.push(course)
                break
              case 5:
                newTableData[slotIndex].friday.push(course)
                break
              case 6:
                newTableData[slotIndex].saturday.push(course)
                break
              case 7:
                newTableData[slotIndex].sunday.push(course)
                break
            }
          } else {
            console.warn(`课程${index + 1}没有找到对应的时间段:`, course)
          }
        }
      })

      // 检查每个时间段的数据填充情况
      newTableData.forEach((row, rowIndex) => {
        Object.keys(row).forEach(day => {
          if (day !== 'timeSlot' && row[day].length > 0) {
            console.log(`${row.timeSlot} ${day}有${row[day].length}门课`)
          }
        })
      })

      tableData.value = newTableData
    }

    // 组件挂载时获取数据
    onMounted(() => {
      getScheduleData()
    })

    return {
      loading,
      scheduleData,
      tableData
    }
  }
}
</script>

<style scoped>
.my-schedule-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.schedule-table-wrapper {
  margin-top: 20px;
}

.course-item {
  padding: 8px;
  background-color: #f0f9ff;
  border-radius: 4px;
  margin: 2px;
  margin-bottom: 8px;
}

.course-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.course-info {
  font-size: 12px;
  color: #666;
}

.course-week {
  font-size: 11px;
  color: #999;
  margin-top: 2px;
}
</style>